package org.paybiz.core.payplatform.bill99.service;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.paybiz.constant.PayConstant;
import org.paybiz.constant.ErrorConstant;
import org.paybiz.core.payplatform.bill99.entity.RmbPayResult;
import org.paybiz.core.payplatform.bill99.util.Pkipair;
import org.paybiz.core.service.callback.AbstractPayCallback;
import org.paybiz.model.PayResultDO;
import org.paybiz.util.DynamicConfig;
import org.springframework.stereotype.Service;

/**
 * 支付回调
 * @author nassir.wen
 * @date 2013-1-8上午9:48:58
 * @company: MSD. 
 * @copyright: Copyright (c) 2013
 */
@Service("bill99CallbackService")
public class Bill99CallbackServiceImpl extends AbstractPayCallback {

    private static final Log logger = LogFactory.getLog(Bill99CallbackServiceImpl.class);

    protected PayResultDO verifyResult(HttpServletRequest request,HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        RmbPayResult rmbPayResult = requestParamsParse(request);
        //签名结果
        boolean flag = Pkipair.enCodeByCer(Pkipair.getSignMsgVal(rmbPayResult.createParamsMap()),
                rmbPayResult.getSignMsg());
        int result = 1; //1为失败0为成功
        String errMsg = "";
        String notifyUrl = rmbPayResult.getExt1();
        String orderId = rmbPayResult.getOrderId();
        try {
            if (flag) {
                //交易成功
                if (StringUtils.equals("10", rmbPayResult.getPayResult())) {
                    logger.info("订单号:" + orderId + "支付成功！");
                    result = 0;
                } else {
                    logger.info("订单号:" + orderId + "支付未成功！");
                }
            } else {
                logger.info("交易签名被篡改！");
                errMsg = ErrorConstant.SIGN_FAIL_ID;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        PayResultDO payResultDO = new PayResultDO();
        payResultDO.setPayMoney(Integer.parseInt(rmbPayResult.getOrderAmount()));
        payResultDO.setOrderId(orderId);
        payResultDO.setPaySerialId(rmbPayResult.getDealId());
        payResultDO.setResult(result);
        payResultDO.setPayType(PayConstant.BILL99);
        payResultDO.setResultUrl(notifyUrl);
        payResultDO.setErrMsg(errMsg);
        return payResultDO;
    }

    private RmbPayResult requestParamsParse(HttpServletRequest request) {
        RmbPayResult rmbPayResult = new RmbPayResult();
        //用于最后链接跳转
        String ext1 = request.getParameter("ext1");
        //签名
        String signMsg = request.getParameter("signMsg");
        //处理结果， 10支付成功，11 支付失败，00订单申请成功，01 订单申请失败
        String payResult = request.getParameter("payResult");

        rmbPayResult.setMerchantAcctId(request.getParameter("merchantAcctId"));
        rmbPayResult.setVersion(request.getParameter("version"));
        rmbPayResult.setLanguage(request.getParameter("language"));
        rmbPayResult.setSignType(request.getParameter("signType"));
        //支付方式，一般为00，代表所有的支付方式。如果是银行直连商户，该值为10,该值与提交时相同。
        rmbPayResult.setPayType(request.getParameter("payType"));
        //银行代码，如果payType为00，该值为空；如果payType为10,该值与提交时相同。
        rmbPayResult.setBankId(request.getParameter("bankId"));
        //订单号
        rmbPayResult.setOrderId(request.getParameter("orderId"));
        rmbPayResult.setOrderTime(request.getParameter("orderTime"));
        //订单金额，金额以“分”为单位，商户测试以1分测试即可，切勿以大金额测试,该值与支付时相同。
        rmbPayResult.setOrderAmount(request.getParameter("orderAmount"));
        // 快钱交易号，商户每一笔交易都会在快钱生成一个交易号。
        rmbPayResult.setDealId(request.getParameter("dealId"));
        //银行交易号 ，快钱交易在银行支付时对应的交易号，如果不是通过银行卡支付，则为空
        rmbPayResult.setBankDealId(request.getParameter("bankDealId"));
        rmbPayResult.setDealTime(request.getParameter("dealTime"));
        //商户实际支付金额 以分为单位。比方10元，提交时金额应为1000。该金额代表商户快钱账户最终收到的金额。
        rmbPayResult.setPayAmount(request.getParameter("payAmount"));
        //费用，快钱收取商户的手续费，单位为分。
        rmbPayResult.setFee(request.getParameter("fee"));
        //扩展字段1，该值与提交时相同。
        rmbPayResult.setExt1(ext1);
        rmbPayResult.setExt2(request.getParameter("ext2"));
        rmbPayResult.setPayResult(payResult);
        rmbPayResult.setErrCode(request.getParameter("errCode"));
        rmbPayResult.setSignMsg(signMsg);
        return rmbPayResult;
    }

    /**
     * @author nassir.wen
     * @date 2013-1-10下午3:03:21
     * @see org.paybiz.core.service.callback.msd.payCenter.msdPay.service.AbstractPayCallback#send(int)
     * @param result
     * @return
     */
    @Override
    protected String send(int result) {
        if (result == PayConstant.RESULT_SUCCESS) {
            /**
             * 由于快钱后台回调要跳转链接而且参数和前台回调一样，那么就直接回调到前台回调地址
             * 也就是说快钱的是先后台回调，做得真恶心.
             */
            StringBuilder redirectUrl = new StringBuilder(200);
            String payConfirmUrl = DynamicConfig.getInstance().getValue(PayConstant.PAYCENTER_URL)
                    + "/payCenter/bill99PayConfirm.html";
            redirectUrl.append("<result>").append(result).append("</result><redirecturl>").append(payConfirmUrl)
                    .append("</redirecturl>");
            logger.info("异步回调成功");
            return redirectUrl.toString();
        } else {
            logger.info("异步回调失败");
            return null;
        }
    }

}
